package com.neuedu.xkxt.controller;

import com.neuedu.xkxt.dto.SignInDTO;
import com.neuedu.xkxt.dto.SignUpDTO;
import com.neuedu.xkxt.model.Student;
import com.neuedu.xkxt.model.Teacher;
import com.neuedu.xkxt.result.R;
import com.neuedu.xkxt.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@CrossOrigin
@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private UserService userService;
    @GetMapping("findUsername")
    public R findUsername(@RequestParam String username){
        Teacher teacher = userService.findUserByTeacherName(username);
        if(teacher != null){
            return new R(500,"用户名不可用",null);

        }else{
            Student student = userService.findUserByStudentName(username);
            if(student != null){
                return new R(500,"用户名不可用",null);
            }else{
                return new R(200,"用户名可用",null);
            }
        }
    }
    @PostMapping("signUp")
    public R signUp(@RequestBody SignUpDTO signUpDTO){
        String username = signUpDTO.getUsername();
        String password = signUpDTO.getPassword();
        String gender=signUpDTO.getGender();
        Student student = new Student();
        student.setName(username);
        student.setPassword(password);
        student.setGender(gender);
        int result=userService.addStudent(student);
        if(result>0){
            return new R(200,"注册成功");
        }else {
            return new R(500,"注册失败");
        }
    }

    @PostMapping("signIn")
    public R signIn(@RequestBody SignInDTO signInDTO) {
        String username = signInDTO.getUsername();
        String password = signInDTO.getPassword();
        System.out.println("-----username:"+ username + ",password:" + password);
        Teacher teacher = userService.findUserByTeacherName(username);
        if (teacher != null) {
            if (teacher.getPassword().equals(password)) {
                return new R(200,"教师登录成功",teacher);
            } else {
                return new R(500,"教师登录失败",null);
            }
        } else {
            Student student = userService.findUserByStudentName(username);
            if (student!= null) {
                if(student.getPassword().equals(password)) {
                    return new R(201,"学生登录成功",student);
                }else{
                    return new R(501,"学生登录失败",null);
                }

            }else{
                return new R(505,"用户名不存在",null);

            }
        }
    }

}

